import { defineStore } from 'pinia'
import type { ICart } from '@/types/types'

export const useCartStore = defineStore('cart', {
    state() {
        return {
            goodsList: [] as Array<ICart>,
            stateAll: false, // 全选功能
        }
    },
    actions: {
        saveGoodsList(data: any) {
            this.goodsList = data
            console.log(this.goodsList)
        },
        // 单选功能
        singleCheck(id: number) {
            const goods: ICart | undefined = this.goodsList.find(
                item => item.id === id
            )
            if (goods) {
                goods.state = !goods.state
            }
            this.stateAll = this.goodsList.every(item => item.state)
        },

        // 全选功能
        checkAll() {
            this.stateAll = !this.stateAll
            this.goodsList.forEach(item => (item.state = this.stateAll))
        },

        // 删除商品
        deleteGoods(id: number) {
            const index = this.goodsList.findIndex(item => item.id === id)
            this.goodsList.splice(index, 1)
        },
    },
    getters: {
        // 总价格
        totalPrice(): number {
            const sum = this.goodsList.reduce(
                // preventvalue 先前值  currentvalue 当前值
                (preventvalue, currentvalue) =>
                    preventvalue +
                    (currentvalue.state
                        ? currentvalue.price * currentvalue.num
                        : 0),
                0
            )
            return Number(sum.toFixed(2)) * 100
        },

        // 已选中商品
        checkGoods(): Array<ICart> {
            const check = this.goodsList.filter(item => item.state === true)
            return check
        },
    },
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'cart', //设置存储的key
                storage: localStorage, //表示存储在localStorage
            },
        ],
    },
})
